package com.yangyouli.unity_demo_server.service.impl;

import java.util.ArrayList;
import java.util.List;

import com.yangyouli.unity_demo_server.annotation.Inject;
import com.yangyouli.unity_demo_server.annotation.Injectable;
import com.yangyouli.unity_demo_server.dao.UserVoDao;
import com.yangyouli.unity_demo_server.entity.UserVo;
import com.yangyouli.unity_demo_server.server.Client;
import com.yangyouli.unity_demo_server.server.RoomObj;
import com.yangyouli.unity_demo_server.server.serializeModel.Room;
import com.yangyouli.unity_demo_server.server.serializeModel.RoomUser;
import com.yangyouli.unity_demo_server.service.RoomService;
import com.yangyouli.unity_demo_server.util.ThreadLocalHelper;

@Injectable
public class RoomServiceImpl implements RoomService{

	@Inject
	UserVoDao userVoDao;
	
	@Override
	public Room getByRoomObj(RoomObj roomObj) {
		if (roomObj == null) return  null;
		UserVo master = userVoDao.findByUserId(roomObj.getMaster().getUserId());
		List<Integer> ids = new ArrayList<>();
		for (Client c : roomObj.getClients()) {
			ids.add(c.getUserId());
		}
		List<UserVo> userVoList = null;
		List<UserVo> userVoListRightOrder = new ArrayList<>();
		if (ids.size() > 0) {
			userVoList = userVoDao.batchQueryByUserIds(ids);
			// 批量查询出来的顺序可能不对，手动调整顺序
			for (int i = 0; i < ids.size(); i++) {
				for (int j = 0; j < userVoList.size(); j++) {
					if (ids.get(i) == userVoList.get(j).getId()) {
						userVoListRightOrder.add(userVoList.get(j));
						userVoList.remove(j);
						break;
					}
				}
			}
		}
 		
		Room room = new Room(roomObj.getRoomId(), userVoToRoomUser(master, roomObj.getMasterPosition()), 
				userVoListToRoomUserList(userVoListRightOrder, roomObj.getClientsPosition()), roomObj.getItems(), 
				roomObj.getMaxPeople(), roomObj.getMode(), roomObj.isStart());
		return room;
	}
	

	@Override
	public Room getByRoomObj(String roomId) {
		RoomObj roomObj = ThreadLocalHelper.getClient().getServer().getRoom(roomId);
		return getByRoomObj(roomObj);
	}
	
	private RoomUser userVoToRoomUser (UserVo userVo, int position) {
		if (userVo == null) return null;
		return new RoomUser(userVo.getId(), userVo.getNickname(), userVo.getUserData().getHeadImgName(), 
				userVo.getUserData().getLevel(), position);
	}
	
	private List<RoomUser> userVoListToRoomUserList (List<UserVo> userVoList, List<Integer> positionList) {
		if (userVoList == null) return null; 
		List<RoomUser> roomUserList = new ArrayList<>();
		for (int i = 0; i < userVoList.size(); i++) {
			roomUserList.add(userVoToRoomUser(userVoList.get(i), positionList.get(i)));
		}
		return roomUserList;
	}

}
